import {messages} from "share/common";
/**
 * created by jsq on 2017/11/25
 */
import React from 'react'
import { connect } from 'react-redux'
import ResizeTable from 'components/resize-table'
import { Button, Popover, Badge, Form } from 'antd';
import SearchArea from 'components/search-area';
import "styles/budget-setting/budget-organization/budget-item-map/budget-item-map.scss"
import budgetService from 'containers/budget-setting/budget-organization/budget-item-map/budget-item-map.service'
import SlideFrame from 'components/slide-frame'
import AddBudgetItemMap from 'containers/budget-setting/budget-organization/budget-item-map/add-budget-item-map'
import menuRoute from "routes/menuRoute";

class BudgetItemMap extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      data: [],
      paramsKey: 0,
      sourceType: [],
      searchParams: {
        groupCode: "",
        groupName: "",
        orgId: this.props.id
      },
      pagination: {
        current: 0,
        page: 0,
        total: 0,
        pageSize: 10,
      },
      paramValueMap: {},
      info: {},
      searchForm: [
        {
          type: 'input',
          id: 'groupCode',
          label: messages('budget-setting.key70'/*匹配组编码*/),
        },
        {
          type: 'input',
          id: 'groupName',
          label: messages('budget-setting.key73'/*匹配组名称*/),
        },
      ],
      columns: [
        {
          title: messages('budget-setting.key75'/*优先级*/), dataIndex: "priority", width: '15%',
        },
        {
          title: messages('budget-setting.key70'/*匹配组编码*/), dataIndex: "groupCode", width: '25%',
        },
        {
          title: messages('budget-setting.key73'/*匹配组名称*/), dataIndex: "groupName", width: '25%', render: value => <Popover content={value}>{value}</Popover>
        },
        {
          title: messages('common.column.status')/*状态*/, dataIndex: "enabled", width: '15%', render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
                   text={enabled ? messages("common.status.enable") : messages("common.status.disable")}/>)
        },
        {
          title: messages('common.operation'), key: 'operation', width: '20%', render: (text, record, index) => (
            <div><a style={{marginLeft: 12}}
                    onClick={(e) => this.operateItem(e, record,  'edit')}>{messages('common.edit')/*编辑*/}</a>
              <a style={{marginLeft: 12}}
                 onClick={(e) => this.operateItem(e,record,  'view')}>{messages('budget-setting.key90'/*项目映射*/)}</a>
            </div>
          )
        },
      ],
      selectedEntityOIDs: [],    //已选择的列表项的OIDs
      showInfoModal: false,

    };
    this.getList();
  }

  //获取预算项目映射数据
  getList() {
    let params = Object.assign({}, this.state.searchParams);
    params.page = this.state.pagination.page;
    params.size = this.state.pagination.pageSize;
    if (!this.state.loading) {
      this.setState({loading: true})
    }
    budgetService.getMatchGroups(params.orgId, params.groupCode, params.groupName, params.page, params.size).then((response) => {
      let paramsKey = this.state.paramsKey;
      response.data.map((item, index) => {
        item.key = paramsKey++;
        item.edit = false;
        item.item = [{id: item.budgetItemId, itemName: item.budgetItemName}];
        item.detail = [{id: item.sourceItemId, name: item.sourceItemName}]
      });
      let pagination = this.state.pagination;
      pagination.total = Number(response.headers['x-total-count']);
      this.setState({
        pagination,
        loading: false,
        data: response.data,
        paramsKey
      })
    }).catch(e=>{
      this.setState({loading: false});
    })
  }

  handleSearch = (values) => {
    let searchParams = this.state.searchParams;
    searchParams.groupCode = values.groupCode === undefined ? "" : values.groupCode;
    searchParams.groupName = values.groupName === undefined ? "" : values.groupName;

    this.setState({
      searchParams,
      loading: true,
      pagination: {
        ...this.state.pagination,
        pageSize: 10
      }
    }, () => {
      this.getList()
    })
  };

  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    let temp = this.state.pagination;
    temp.page = pagination.current - 1;
    temp.current = pagination.current;
    temp.pageSize = 10;
    this.setState({
      pagination: temp
    }, () => {
      this.getList();
    })
  };
  clear = () => {
    this.setState({
      page: 0,
      searchParams: {
        groupCode: "",
        groupName: "",
        orgId: this.props.id
      }
    }, () => {
      this.getList();
    });
  };

  operateItem = (e,record, type) => {
    e.preventDefault();
    e.stopPropagation();
    if (type === 'edit') {
      this.setState({showInfoModal: true, info: record})
    }
    if (type === 'view') {
      this.context.router.replace(menuRoute.getRouteItem('budget-item-map-setting', 'key').url.replace(':id', this.props.id).replace(':groupId', record.id));
    }
  }
  handleAdd = () => {
    this.setState({showInfoModal: true, info: {}})
  };

  handleSave = () => {

  };
  callbackUpdate = (info) => {
    let {data, pagination} = this.state;
    let ifExist = false;
    data && data.length > 0 && data.map((item, index) => {
      if (item.id === info.id) {
        ifExist = true;
        data[index] = info;
      }
    })
    if (!ifExist) {
      pagination.total += 1;
      data.unshift(info);
    }
    this.setState({data, pagination})
  }
  closeModal=()=>{
    console.log('come in');
    this.setState({ showInfoModal: false, info: {} });
  }

  render() {
    const { loading, searchForm, data, pagination, columns, info, showInfoModal } = this.state;
    return (
      <div className="budget-item-map">
        <SearchArea searchForm={searchForm} submitHandle={this.handleSearch} clearHandle={this.clear} />
        <div className="table-header">
          <div className="table-header-buttons">
            <Button type="primary" size="middle" onClick={this.handleAdd}>{messages('budget-setting.key91'/*创建匹配组*/)}</Button>
          </div>
          <div className="table-header-title">{messages('common.total', { total: `${pagination.total}` })}</div>  {/*共搜索到*条数据*/}
        </div>
        <Form
          className="ant-advanced-search-form">
          <ResizeTable
            dataSource={data}
            columns={columns}
            loading={loading}
            onRow={record => ({
              onClick: (e) =>  this.operateItem(e,record, 'view')
            })}
            rowKey='id'
            bordered
            onChange={this.onChangePager}
            pagination={pagination}
            size="middle" />
        </Form>
        <SlideFrame show={showInfoModal}
                    title={info.id ? messages('budget-setting.key91'/*创建匹配组*/) : messages('budget-setting.key92'/*编辑匹配组*/)}
                    hasFooter={false}
                    params={{
                      info: info,
                      orgId: this.props.id,
                      updateAfter: this.callbackUpdate,
                      onClose: this.closeModal
                    }}
                    content={AddBudgetItemMap}
                    onClose={this.closeModal}
                    afterClose={this.closeModal}
                    width="800px"/>
      </div>
    )
  }

}
BudgetItemMap.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization,
    company: state.login.company,
  }
}

export default connect(mapStateToProps)(BudgetItemMap);


